import React, { useMemo } from "react";
import {
  BrowserRouter as Router,
  Route,
  Switch,
  Redirect,
} from "react-router-dom";
import { useSelector } from "react-redux";
import LoginPage from "../layout/login";
import AuthWrapper from "../components/AuthWrapper";
import MainLayout from "../components/MainLayout";
import NotFound from "../components/NotFound";
import Home from "../views/home";

const loadComponent = (componentPath) => {
  console.log("Loading component:", componentPath);
  return React.lazy(() =>
    import(`../views/${componentPath}.jsx`).catch((err) => {
      console.error(`Error loading component: ${componentPath}`, err);
      return { default: () => <NotFound /> };
    })
  );
};

const PrivateRoute = ({ component: Component, ...rest }) => {
  const isAuthenticated = useSelector((state) => !!state.user.userName);
  return (
    <Route
      {...rest}
      render={(props) =>
        isAuthenticated ? (
          <MainLayout>
            <React.Suspense fallback={<div>Loading...</div>}>
              <Component {...props} />
            </React.Suspense>
          </MainLayout>
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );
};

const generateRoutes = (menus) => {
  const routes = [];

  const addRoute = (menu) => {
    if (menu.component) {
      routes.push(
        <PrivateRoute
          key={menu.path}
          exact
          path={menu.path}
          component={loadComponent(menu.component)}
        />
      );
    }

    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(addRoute);

      if (!menu.component) {
        routes.push(
          <Redirect
            key={`${menu.path}-redirect`}
            exact
            from={menu.path}
            to={menu.children[0].path}
          />
        );
      }
    }
  };

  menus.forEach(addRoute);
  return routes;
};

const AppRouter = () => {
  const menus = useSelector((state) => state.user.menus);
  console.log("Menus from state:", menus);

  const routes = useMemo(() => {
    const generatedRoutes = generateRoutes(menus);
    generatedRoutes.unshift(
      <PrivateRoute key="/home" exact path="/home" component={Home} />
    );
    return generatedRoutes;
  }, [menus]);

  console.log("Generated routes:", routes);

  return (
    <Router>
      <AuthWrapper>
        <Switch>
          <Route path="/login" component={LoginPage} />
          <Redirect exact from="/" to="/home" />
          {routes}
          <Route component={NotFound} />
        </Switch>
      </AuthWrapper>
    </Router>
  );
};

export default AppRouter;
